<template>
  <el-card>
    <el-input :disabled="true" class="mb_20" :value="roleName" ></el-input>
    <el-tree
      class="mb_20"
      :data="ToAssignList"
      default-expand-all
      show-checkbox
      node-key="id"
      :default-checked-keys="defaultCheckedList"
      :props="defaultProps"
      @node-click ="nodeClick"
      @check-change ="checkChange"
    >
    </el-tree>
    <el-button type="primary" class="mr_20" @click="OnSave">保存</el-button>
    <el-button @click="unSave">取消</el-button>
  </el-card>
</template>

<script>
import { getToAssign ,setdoAssign} from "@/api/pro/useRole";
import {cloneDeep} from "loadsh"
export default {
  data() {
    return {
      ToAssignList: [],
      defaultCheckedList :[],
      defaultProps: {
        children: "children",
        label: "name",
      },
      roleName: "",
      roleid:''
    };
  },
  methods: {
    async getToAssignList() {
      try {
        let result = await getToAssign(this.roleid);
        this.ToAssignList = result.data.children;
        console.log( this.ToAssignList);
        let arr =  this.filterToAssignList(cloneDeep(this.ToAssignList));
        console.log(arr);
        let newarr = this.filterToAssignID( arr)
       
         this.defaultCheckedList =  this.fliters(newarr).map(e=>{
          return e.id
        });
        
      } catch (error) {
        console.log(error);
      }
    },
    // 递归获取选中节点的数组
    filterToAssignList(list){
     return list.filter(e=>{
        e.children =  this.filterToAssignList(e.children)
        return  e.select == true
      })

    },
    fliters(list){
      return list.filter(e=>{
          e.children =  this.fliters(e.children)
        return  e.level == 4
      })
    },
    // 递归得到id
    filterToAssignID(list){ 
      return list.reduce((pre,item)=>{
        
           return pre.concat(item).concat(...this.filterToAssignID(item.children))
       
       
      },[])
    },
    // 点击取消的回调
    unSave() {
      this.$router.back();
    },
    // 节点被点击时的回调
    nodeClick(e){
      // console.log(e);
    },
    // 节点选中状态发生变化时的回调
    checkChange(e,chec,a){
      console.log(e);
    },
    // 保存的功能函数
    async setOnSave(roleId){
      try {
        let result = await setdoAssign(this.roleid,roleId)
      } catch (error) {
        console.log(error);
      }
    },
    // 点击保存的回调
    OnSave(){

      this.setOnSave()
    }
  },
  mounted() {
  
    this.roleName = this.$route.params.roleName
    this.roleid = this.$route.params.roleid
    this.getToAssignList();
  },
};
</script>

<style>
</style>